
import React, { Component } from 'react'
import { Divider, Alert, Menu, Dropdown, Tabs, Row, Col, Card, Button, Space, Switch, Tooltip, Modal, Form, Input, DatePicker, message, Select } from 'antd';
import moment from 'moment'
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { HomeOutlined, PlusOutlined, FormOutlined, DeleteOutlined, ExclamationCircleOutlined, LockOutlined, CheckCircleOutlined } from '@ant-design/icons';
import { ReadConfig, writeConfig } from "@/services/homeSet";
import ImageBox from '@/components/ImageBox';

import styles from "./index.less"
import { HomeList } from "@/utils/config.js"
import MotionLayout from '@/layouts/MotionLayout';
class HomeSet extends Component {
  constructor(props) {
    super(props)

    this.state = {
      activeKey: "banner",
      banner: [],
      newsitems: [],
      ability: [],
      imgsider: [],
      calendarsider: [],
      imgsay: [],
      album: [],
      modalVisible: false,
      obj: {},
      isAdd: false,
    }
    this.Load();
  }
  async Load() {
    let banner = await ReadConfig({ name: "banner" });
    if (banner.success) {
      this.setState({
        banner: JSON.parse(banner.result).sort((a, b) => (Number(b.orderNum) - Number(a.orderNum))).map((item, index) => ({ ...item, index }))
      })
    }
    let newsitems = await ReadConfig({ name: "newsitems" });
    if (newsitems.success) {
      this.setState({
        newsitems: JSON.parse(newsitems.result).sort((a, b) => (Number(b.orderNum) - Number(a.orderNum))).map((item, index) => ({ ...item, index }))
      })
    }
    let ability = await ReadConfig({ name: "ability" });
    if (ability.success) {
      this.setState({
        ability: JSON.parse(ability.result).sort((a, b) => (Number(b.orderNum) - Number(a.orderNum))).map((item, index) => ({ ...item, index }))
      })
    }
    let imgsider = await ReadConfig({ name: "imgsider" });
    if (imgsider.success) {
      this.setState({
        imgsider: JSON.parse(imgsider.result).sort((a, b) => (Number(b.orderNum) - Number(a.orderNum))).map((item, index) => ({ ...item, index }))
      })
    }
    let calendarsider = await ReadConfig({ name: "calendarsider" });
    if (calendarsider.success) {
      this.setState({
        calendarsider: JSON.parse(calendarsider.result).sort((a, b) => (Number(b.orderNum) - Number(a.orderNum))).map((item, index) => ({ ...item, index }))
      })
    }
    let imgsay = await ReadConfig({ name: "imgsay" });
    if (imgsay.success) {
      this.setState({
        imgsay: JSON.parse(imgsay.result).sort((a, b) => (Number(b.orderNum) - Number(a.orderNum))).map((item, index) => ({ ...item, index }))
      })
    }
    let album = await ReadConfig({ name: "album" });
    if (album.success) {
      this.setState({
        album: JSON.parse(album.result).sort((a, b) => (Number(b.orderNum) - Number(a.orderNum))).map((item, index) => ({ ...item, index }))
      })
    }
  }
  async handleDeal({ json, name, type = "添加" }) {
    const hide = message.loading(`正在${type}`);
    try {
      const resWrite = await writeConfig({ name, jsonString: JSON.stringify(json) });
      if (!resWrite.success) {
        message.error(`${type}失败，${resWrite.result}`);
        hide();
        return false;
      }
      hide();
      message.success(`${type}成功`);
      this.setState({
        [name]: json
      });
      return true;
    } catch (error) {
      hide();
      message.error(`${type}异常，${error}`);
      return false;
    }
  }
  async handleHome(params) {
    const cname = HomeList.find(item => item.name == params.key).cname;
    const hide = message.loading(`正在添加到${cname}`);
    try {
      const resRead = await ReadConfig({ name: params.key });

      // if (!resRead.success) {
      //   message.error(`查询失败，${resRead.result}`);
      //   hide();
      //   return false;
      // }
      const addObj = {
        title: params.title ? params.title : "",
        content: params.content ? params.content : "",
        time: params.time ? params.time : "",
        href: params.href ? params.href : "",
        src: params.src ? params.src : "",
        isEnable: false,
        orderNum: "0",
      }

      const json = [addObj, ...JSON.parse(resRead.rescode == 200 ? resRead.result : "[]")];
      const resWrite = await writeConfig({ name: params.key, jsonString: JSON.stringify(json) });
      if (!resWrite.success) {
        message.error(`写入失败，${resWrite.result}`);
        hide();
        return false;
      }
      hide();
      message.success(`添加到${cname}成功`);
      this.Load();
      return true;
    } catch (error) {
      hide();
      message.error(`异常，${error}`);
      return false;
    }
  };
  createCol(item, index, name) {
    return (
      <Col key={index} xxl={6} xl={8} lg={12} md={24} sm={24} xs={24} >
        <Card
          cover={
            name == "newsitems" || name == "calendarsider" ? null :
              <img alt="" src={item.src} />
          }
          title={
            item.isEnable ? <span className={'ant-btn-link'} ><CheckCircleOutlined style={{ marginRight: 3 }} />启用</span> :
              <span style={{ color: "#aaa" }}><LockOutlined style={{ marginRight: 3 }} />禁用</span>
            // <Switch
            //   checked={item.isEnable == true}
            //   checkedChildren="启用" unCheckedChildren="禁用" />
            // name == "banner" || name == "ability" || name == "imgsider" ? null :
            //   item.time
          }
          extra={
            <Space>
              <Dropdown
                overlay={
                  <Menu
                    onClick={async ({ key }) => {
                      await this.handleHome({ key, ...item, })
                    }}
                  >
                    {
                      HomeList.map(item => <Menu.Item key={item.name}>{item.cname}</Menu.Item>)
                    }
                  </Menu>
                }
              >
                <Button
                  onClick={() => {
                  }}
                  size="small" type="default" icon={<HomeOutlined />} ></Button>
              </Dropdown>
              <Button
                onClick={() => {
                  this.setState({
                    obj: {
                      ...item,
                      time: item.time == "" || item.time == null ? moment() : moment(item.time),
                    },
                    modalVisible: true,
                    isAdd: false,
                  })
                }}
                size="small" type="dashed" icon={<FormOutlined />}></Button>
              <Button
                onClick={() => {
                  Modal.confirm({
                    title: '是否确认删除?',
                    icon: <ExclamationCircleOutlined />,
                    onOk: async () => {
                      const json = this.state[name].filter(fitem => fitem.index != item.index);
                      const success = await this.handleDeal({
                        json,
                        name: this.state.activeKey,
                        type: "删除",
                      })
                    },
                  });
                }}
                size="small" type="dashed" icon={<DeleteOutlined />}></Button>
            </Space>
          }
        >
          <Card.Meta title={<Tooltip title={item.title}>
            <span>{
              name == "calendarsider" ? (item.title ? item.title : `${item.timeSpace}·${item.place}`) : (name == "banner" ? null :
                item.title)
            }</span>
          </Tooltip>} description={
            name == "album" || name == "banner" || name == "ability" || name == "imgsider" || name == "imgsay" || name == "calendarsider" ? null :
              item.content
          } />
        </Card>
      </Col>
    )
  }
  render() {
    return (
      <PageHeaderWrapper>
        <MotionLayout>
          <Card>
            <Tabs type="line" className={styles.block} activeKey={this.state.activeKey} tabPosition="top"
              // tabBarStyle={{
              //   backgroundColor: "#fff",
              // }}

              onChange={(activeKey) => {
                this.setState({ activeKey })
              }}>
              {
                HomeList.map((item, index) => <Tabs.TabPane tab={item.cname} key={item.name}>
                  <div style={{ height: "16px" }}></div>
                  <Button
                    onClick={() => {
                      this.setState({ modalVisible: true, isAdd: true, obj: { isEnable: false, orderNum: "0" } })
                    }}
                    type="dashed" size="large" block={true}><PlusOutlined />添加</Button>
                  <div style={{ height: "16px" }}></div>
                  <Row gutter={[8, 8]}>
                    {this.state[item.name].map((sitem, sindex) =>
                      this.createCol(sitem, sindex, item.name)
                    )}
                  </Row>
                </Tabs.TabPane>
                )
              }
            </Tabs>
          </Card>
        </MotionLayout>
        <Modal
          destroyOnClose
          title={HomeList.find(item => item.name == this.state.activeKey).cname}
          visible={this.state.modalVisible}
          onCancel={() => this.setState({ modalVisible: false })}
          onOk={() => {
            this.myform.submit();
          }}
        >
          {HomeList.find(item => item.name == this.state.activeKey).tip == "" ? null :
            <Alert style={{ marginBottom: 20 }} message={HomeList.find(item => item.name == this.state.activeKey).tip} type="warning" showIcon />
          }


          <Form
            initialValues={{
              ...this.state.obj,
            }}
            ref={(_) => (this.myform = _)}
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 19 }}
            onFinish={async (fieldsValue) => {
              const name = this.state.activeKey;
              let obj = {};
              if (!fieldsValue.time) {
                obj = fieldsValue
              }
              else {
                obj = { ...fieldsValue, time: fieldsValue.time.format("YYYY-MM-DD") };
              }
              if (this.state.isAdd) {
                //添加
                const json = [...this.state[name], { ...obj, index: -1 }].sort((a, b) => (Number(b.orderNum) - Number(a.orderNum))).map((item, index) => ({ ...item, index }));
                const success = await this.handleDeal({ name, json, type: "添加" });
                if (success) {
                  this.setState({
                    modalVisible: false,
                  })
                }
              }
              else {
                //更新
                const json = this.state[name].map(item => item.index == this.state.obj.index ? obj : item).sort((a, b) => (Number(b.orderNum) - Number(a.orderNum))).map((item, index) => ({ ...item, index }));
                const success = await this.handleDeal({ name, json, type: "更新" });
                if (success) {
                  this.setState({
                    modalVisible: false,
                  })
                }
              }
            }}
          >
            {
              this.state.activeKey == "banner" || this.state.activeKey == "calendarsider" ? null :
                <Form.Item
                  label="标题"
                  name="title"
                  rules={[{ required: true }]}
                >
                  <Input />
                </Form.Item>
            }
            {
              this.state.activeKey == "album" || this.state.activeKey == "banner" || this.state.activeKey == "imgsider" || this.state.activeKey == "imgsay" || this.state.activeKey == "calendarsider" ? null :
                <Form.Item
                  label="正文摘要"
                  name="content"
                  rules={[{ required: true }]}
                >
                  <Input.TextArea rows={5} maxLength={100} />
                </Form.Item>
            }
            {
              this.state.activeKey == "newsitems" || this.state.activeKey == "calendarsider" ? null :
                <Form.Item
                  label="图片"
                  name="src"
                  rules={[{ required: true, message: "请上传图片" }]}
                >
                  <ImageBox arr={[]} maxSize={3} action="/api/homeSet/uploadImg" />
                </Form.Item>
            }
            {
              this.state.activeKey == "banner" || this.state.activeKey == "ability" || this.state.activeKey == "imgsider" || this.state.activeKey == "imgsay" || this.state.activeKey == "calendarsider" ? null :
                <Form.Item
                  label="日期"
                  name="time"
                  rules={[{ required: true }]}
                >
                  <DatePicker />
                </Form.Item>
            }
            {
              this.state.activeKey == "calendarsider" ? <Form.Item
                label="关键字1"
                name="timeSpace"
                rules={[{ required: true }]}
              >
                <Input />
                {/* <Input placeholder="如：9:00-16:00" /> */}
              </Form.Item> : null
            }
            {
              this.state.activeKey == "calendarsider" ? <Form.Item
                label="关键字2"
                name="place"
                rules={[{ required: true }]}
              >
                <Input />
                {/* <Input placeholder="如：综合楼多媒体教室" /> */}
              </Form.Item> : null
            }
            {
              this.state.activeKey == "calendarsider" ? <Form.Item
                label="图标分类"
                name="by"
                rules={[{ required: true }]}
              >
                <Select options={[
                  { label: "大事记", value: "大事记" },
                  { label: "讲座活动", value: "讲座活动" },
                  { label: "领导视察", value: "领导视察" },
                  { label: "荣耀时刻", value: "荣耀时刻" },
                  { label: "企业实践", value: "企业实践" },
                  { label: "通知公告", value: "通知公告" },
                  { label: "新纪录", value: "新纪录" },
                  { label: "宣传视频", value: "宣传视频" },
                  { label: "质量报告", value: "质量报告" },
                ]} />
              </Form.Item> : null
            }
            {
              this.state.activeKey == "calendarsider" ? <Form.Item
                label="栏目"
                name="type"
                rules={[{ required: true }]}
              >
                <Input />
              </Form.Item> : null
            }
            {
              this.state.activeKey == "calendarsider" || this.state.activeKey == "ability" ? <Form.Item
                label="地址"
                name="pre"
                rules={[{ required: true }]}
              >
                <Input />
                {/* <Input placeholder="如：活动、通知等" /> */}
              </Form.Item> : null
            }
            <Form.Item
              label="链接地址"
              name="href"
              rules={[{ required: true }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="是否启用"
              name="isEnable"
              valuePropName="checked"
              rules={[{ required: true }]}
            >
              <Switch checkedChildren={"启用"} unCheckedChildren={"禁用"} />
            </Form.Item>
            <Form.Item
              label="显示顺序"
              name="orderNum"
              rules={[{ required: true }]}
            >
              <Input type="number" />
            </Form.Item>
          </Form>
        </Modal>
      </PageHeaderWrapper>
    )
  }
}
export default HomeSet
